package com.pubsys.main.client.util;


import java.util.HashMap;

import com.google.gwt.user.client.History;

/**
 * This class adds some functionality to the default History class from GWT.
 * Adds parameters capabilities in the #defaultGWTHistoryAnchor[?param1=value1&param2=value2] format
 * @author Martin Reus
 */
public abstract class HistoryTokensHelper extends History{
	public static char _PARAMETERSEPARATOR = '&';
  	
	/**
	 * Appends or updates a parameterName (from browser URL) creating a new history token
	 * ValueChanged will also fire
	 * @param parameterName
	 * @param parameterValue
	 */
    public static void setHistoryTokenParameter(String parameterName, String parameterValue, boolean fireEvent){    	
    	HashMap<String, String> parametersMap = getHistoryTokenParameters();
    	parametersMap.put(parameterName, parameterValue);    	
    	setHistoryTokenWithParameters(getPageAnchor(), parametersMap, fireEvent);    	
    }
    
    
    /**
     * Calls the parent method <code>newItem(String)</code> from History class
     * @param token
     */
    public static void setDefaultHistoryToken(String token){
    	newItem(token);
    }
    
    
    
    /**
	 * Sets a new history token (on browser url), in the form "#anchor?param1=arg1_PARAMETERSEPARATORparam2=arg2"
	 * ValueChanged will also fire
	 * @param parameterName
	 * @param parameterValue
	 */
    public static void setHistoryTokenWithParameters(String anchor, HashMap<String, String> parameters, boolean fireEvent){
    	String token = "";
    	
    	if (anchor != null && !anchor.equals("")){
    		token = anchor;
    	}
    	
    	if (parameters != null && !parameters.isEmpty()){
    		token += "?";
    		boolean secondPass = false;
    		for (String parameterName : parameters.keySet()) {
				if (secondPass){
					token += _PARAMETERSEPARATOR;
				}
				token += parameterName + "=" + parameters.get(parameterName);
				secondPass = true;
			}
    	}
    	
    	newItem(token, fireEvent);
    }
    
    
    
    
    
    /**
     * get historyToken parameters
     * 
     * like domaint.tld#anchor?[var=1&var3=2&var3=3]
     * 
     * @param historyToken anchor tag
     * @return hashmap of the parameters
     */
    public static HashMap<String, String> getHistoryTokenParameters() {
    
            //skip if there is no question mark
            if (!getToken().contains("?")) {
                    return new HashMap<String, String>();
            }
            
            // ? position
            int questionMarkIndex = getToken().indexOf("?") + 1;
            
            //get the sub string of parameters var=1&var2=2&var3=3...
            String[] arStr = getToken().substring(questionMarkIndex, getToken().length()).split(String.valueOf(_PARAMETERSEPARATOR));
            HashMap<String, String> params = new HashMap<String, String>();
            for (int i = 0; i < arStr.length; i++) {
                    String[] substr = arStr[i].split("=");
                    try{
                    	//we have to catch an error when "param=" ( no arg is given )
                    	params.put(substr[0], substr[1]);
                    }catch (Exception e) {
                    	//nothing
					}
            }
            return params;
    }
    
    
    /**
     * Gets a param value from the current history token (browser actual url link)
     * @param paramName
     * @return
     */
    public static String getParameterValue(String paramName){
    	if (getHistoryTokenParameters().get(paramName) != null && !getHistoryTokenParameters().get(paramName).equals(""))
    		return getHistoryTokenParameters().get(paramName);
    	return "";
    }
    
    
    
    /**
     * Gets the actual anchor for the page
     * 
     * like domain.tld#[historyToken]?params=1
     *  
     * @param historyToken
     * @return
     */
    public static String getPageAnchor() {
            
		String historyToken = getToken();

        if (!historyToken.contains("?")) {
                return getToken();
        }

        //get just the historyToken/anchor tag
        String[] arStr = historyToken.split("\\?");
        historyToken = arStr[0];

        return historyToken;
    }
    
    
    /**
     * Sets a page anchor, keeping the old parameters
     * @param anchor
     */
    public static void setPageAnchor(String anchor){
    	String historyToken = getToken();
    	
        //skip if there is no question mark
        if (!historyToken.contains("?")) {
                newItem(anchor);
        }else{
        	String[] arStr = historyToken.split("\\?");
        	try{
        		String composition = anchor + "?";
        		for (int i = 1 ; i < arStr.length ; i++) {
					composition += arStr[i];
				}
        		newItem(composition);
        	}catch (Exception e) {
        		
			}
        }
    }
    

    /**
     * Are there params in historyToken?
     * 
     * @return
     */
    public static boolean areParamsInHistoryToken() {
            String s = getToken();
            
            if (s.contains("?")) {
                    return true;
            } else {
                    return false;
            }
    }

	
	
}
